package models

import (
	"gorm.io/gorm"
	"time"
)

// 积分记录
type MMemberScorelog struct {
	ID         int    `gorm:"type:int(10); primaryKey" json:"id"`
	Aid        int    `json:"aid"`   //账户ID
	Mid        int    `json:"mid"`   //会员ID
	Score      int    `json:"score"` //赠送积分
	After      int    `json:"after"` //之后
	Createtime int    `json:"createtime"`
	Remark     string `json:"remark"`
	Type       int    `json:"type"`      //1增加，2减少
	Status     int    `json:"status"`    //状态：0默认，1成功，2回滚
	IsCancel   int    `json:"is_cancel"` //是否取消
}

func (table *MMemberScorelog) TableName() string {
	return "m_member_scorelog"
}

// 增加积分，返回1成功，返回2失败
func ScoreAdd(tx *gorm.DB, Mid int, score int, Aid int, msg string) int {
	//查询用户信息
	var MemData MMember
	err := tx.Model(new(MMember)).Where("id=?", Mid).First(&MemData).Error
	if err != nil {
		return 2
	}
	//为用户增加余额和积分
	upData := map[string]interface{}{
		"score": gorm.Expr("score+?", score),
	}
	err = tx.Model(new(MMember)).Where("id=?", Mid).Updates(&upData).Error
	if err != nil {
		return 2
	}
	//写入积分记录
	scoreData := map[string]interface{}{
		"aid":        Aid,
		"mid":        Mid,
		"score":      score,
		"after":      MemData.Score + score,
		"createtime": int(time.Now().Unix()),
		"remark":     msg,
		"type":       1,
		"status":     0,
		"is_cancel":  0,
	}
	err = tx.Model(new(MMemberScorelog)).Create(&scoreData).Error
	if err != nil {
		return 2
	}
	return 1
}

// 减少积分，返回1成功，返回2失败
func ScoreEdit(tx *gorm.DB, Mid int, score int, Aid int, yscore int, msg string) int {
	//为用户增加余额和积分
	upData := map[string]interface{}{
		"score": gorm.Expr("score-?", score),
	}
	err := tx.Model(new(MMember)).Where("aid=? AND id=?", Aid, Mid).Updates(&upData).Error
	if err != nil {
		return 2
	}
	//写入积分记录
	scoreData := map[string]interface{}{
		"aid":        Aid,
		"mid":        Mid,
		"score":      score,
		"after":      yscore - score,
		"createtime": int(time.Now().Unix()),
		"remark":     msg,
		"type":       2,
		"status":     0,
		"is_cancel":  0,
	}
	err = tx.Model(new(MMemberScorelog)).Create(&scoreData).Error
	if err != nil {
		return 2
	}
	return 1
}
